/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.ysd.modules.app.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysd.common.exception.RRException;
import com.ysd.common.validator.Assert;
import com.ysd.modules.app.dao.UserDao;
import com.ysd.modules.app.entity.UserEntity;
import com.ysd.modules.app.form.LoginForm;
import com.ysd.modules.app.service.UserService;

import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

	@Override
	public UserEntity queryByMobile(String mobile) {
		return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("mobile", mobile));
	}

	@Override
	public long login(LoginForm form) {
		UserEntity user = queryByMobile(form.getMobile());
		Assert.isNull(user, "手机号或密码错误");

		//密码错误
		if(!user.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))){
			throw new RRException("手机号或密码错误");
		}
		//设置在线状态,记录登陆时间
		user.setOnLine(1);
		user.setLoginTime(new Date());
		baseMapper.updateById(user);
		return user.getUserId();
	}

	@Override
	public long updatePwd(Integer uid, String oldPwd, String newPwd, String rePwd) {
		UserEntity user = baseMapper.selectById(uid);
		//密码错误
		if(!user.getPassword().equals(DigestUtils.sha256Hex(oldPwd))){
			throw new RRException("旧密码错误");
		}
		if(!(newPwd !=null && rePwd != null && newPwd.equals(rePwd))) {
			throw new RRException("两次密码不一致");
		}
		user.setPassword(DigestUtils.sha256Hex(newPwd));
		return baseMapper.updateById(user);
	}
}
